package com.suke.czx.modules.wx.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.suke.czx.common.utils.DateUtils;
import com.suke.czx.common.utils.JsonResult;
import com.suke.czx.common.utils.Query;
import com.suke.czx.modules.wx.config.WxMpConfiguration;
import com.suke.czx.modules.wxadmin.entity.DkReadPlanMsgEntity;
import com.suke.czx.modules.wxadmin.entity.DkUserEntity;
import com.suke.czx.modules.wxadmin.service.DkReadPlanMsgService;
import com.suke.czx.modules.wxadmin.service.DkUserService;

import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialFileBatchGetResult;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;

@RestController
@RequestMapping("/wx/send")
public class SendSteateContronller {
	
	private static final Logger logger = LoggerFactory.getLogger(SendSteateContronller.class);
	 
	private static String textContent = "阅读学习提醒\r\n\r\n亲爱的 {0},你参加的《210天学习计划》的课程内容已更新，已有{1}%的同学完成今日学习。"
			+"\r\n\r\n<a href=\"https://go.qun056.com/2/czNw\">请点这里加入班级群，与老师同学交流！（勿重复加）</a>"
			+ "\r\n\r\n点击下方【今日阅读】，完成今日的学习，每天坚持一点点，做更好的自己！\r\n\r\n↓↓↓";
	
	
	@Autowired
	private DkUserService dkUserService;
	
	@Autowired 
	DkReadPlanMsgService dkReadPlanMsgService;
	
	
	@RequestMapping("/planned111111134")
	public String planned(){
		
		String dateStr = DateUtils.getDate(new Date(), 0);
		//1、执行清空消息表；
		dkReadPlanMsgService.deleteAll();
		logger.info("=========>执行定时任务处理发送消息数据-清理数据：" + dateStr );
		//2、数据迁移
		dkReadPlanMsgService.planedSave(dateStr);
		logger.info("=========>执行定时任务处理发送消息数据-迁移数据：" + dateStr );
		return new JsonResult(200,"数据迁移成功，每天凌晨做准备，为发送消息时候减轻服务器负担").toJson();
	}
	
	
	
	@RequestMapping("/msg11111")
	public String send(){
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("page", 1);
		params.put("limit", 2000);
		//查询列表数据
		Query query = new Query(params);
		int i = 0;
		List<Object> id = new ArrayList<Object>();
		List<DkReadPlanMsgEntity> list = dkReadPlanMsgService.queryList(query);
		//判断今日是否还有相关数据要发送，如果没有就返回
		if(list==null||list.size()==0){
			return new JsonResult(200,"数据已经没有啦-定时任务发送用户消息成功！").toJson();
		}
		//=======================B
		for(DkReadPlanMsgEntity plan : list){
			//logger.info("=======>" + user.getNickname() +" : " + user.getOpenid() +"数据推送成功！" );
			//流程走完 不管成功失败 更新状态
			id.add(plan.getId());
		}
		//=======================E
		dkReadPlanMsgService.updateSendStateBatch(id.toArray());
		logger.info("=========>执行定时任务处理发送消息数据-发送数据：" + "第"+ i++ +"波" );
		new Thread(new  Runnable() {
			public void run() {
				for(DkReadPlanMsgEntity plan : list){
					DkUserEntity user = dkUserService.queryObject(plan.getUserId());
					sendMsgToUser(user);
				}
			}
		}).start();	
		
		return new JsonResult(200,"定时任务发送用户消息成功！").toJson();
	}
	@RequestMapping("/msg/{openid}")
	public String sendByOpenid(@PathVariable String openid){
		DkUserEntity user = dkUserService.queryObject(openid);
		int i = sendMsgToUser(user);
		return new JsonResult(200,"ok"+i).toJson();
	}
	@RequestMapping("/token/zhangdewen")
	public String token(){
		WxMpService wxMpService = WxMpConfiguration.getMpServices().get("wx110e4b18284caf04");
		String token;
		try {
			token = wxMpService.getAccessToken();
			return new JsonResult(200,"ok",token).toJson();
		} catch (WxErrorException e) {
			e.printStackTrace();
			return new JsonResult(-1,e.getMessage()).toJson();
		}
	}
	
	@RequestMapping("/material/zhangdewen")
	public String material(String type,int offset ,int count){
		WxMpService wxMpService = WxMpConfiguration.getMpServices().get("wx110e4b18284caf04");
		try {
			WxMpMaterialFileBatchGetResult materialFileBatchGet = wxMpService.getMaterialService().materialFileBatchGet(type, offset, count);
			return new JsonResult(200,"ok",materialFileBatchGet).toJson();
			
		} catch (WxErrorException e) {
			e.printStackTrace();
			return new JsonResult(-1,e.getMessage()).toJson();
		}
	}
	
	@RequestMapping("/tmp/{openid}")
	public String sendTmpByOpenid(@PathVariable String openid){
		try {
			Random ra =new Random();
			DkUserEntity user = dkUserService.queryObject(openid);
			WxMpService wxMpService = WxMpConfiguration.getMpServices().get("wx110e4b18284caf04");
			//发送模板消息
			WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
					.toUser(user.getOpenid())
					.templateId("wxpe7Oxiy4P7fHagjSxnKPHOqRAc5SayCxuxZcFbF68")
					.build();
			templateMessage.addData(new WxMpTemplateData("first", user.getNickname()+",今日课程内容已更新,已有7"+ra.nextInt(10)+"%同学完成今日学习\r\n\r\n", "#000000"));
			templateMessage.addData(new WxMpTemplateData("keyword1", "《210天学习计划》", "#000000"));
			templateMessage.addData(new WxMpTemplateData("keyword2", "学习时长约10分钟\r\n\r\n", "#000000"));
			templateMessage.addData(new WxMpTemplateData("remark", "点击下方【今日阅读】，完成今日的学习，每天坚持一点点，做更好的自己！\r\n\r\n↓↓↓", "#000000"));
			wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
		} catch (WxErrorException e) {
			e.printStackTrace();
		}
		
		return new JsonResult(200,"ok").toJson();
	}
	
	
	
	public int sendMsgToUser(DkUserEntity user){
		WxMpService wxMpService = WxMpConfiguration.getMpServices().get("wx110e4b18284caf04");
		Random ra =new Random();
		WxMpKefuMessage message = WxMpKefuMessage
				  .TEXT()
				  .toUser(user.getOpenid())
				  .content(textContent.replace("{0}", user.getNickname()).replace("{1}","7"+ra.nextInt(10)))
				  .build();
		try {
			if(!wxMpService.getKefuService().sendKefuMessage(message)){
				//发送模板消息
				WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
						.toUser(user.getOpenid())
						.templateId("wxpe7Oxiy4P7fHagjSxnKPHOqRAc5SayCxuxZcFbF68")
						.build();
				templateMessage.addData(new WxMpTemplateData("first", user.getNickname()+",今日课程内容已更新,已有7"+ra.nextInt(10)+"%同学完成今日学习\r\n\r\n", "#000000"));
				templateMessage.addData(new WxMpTemplateData("keyword1", "《210天学习计划》", "#000000"));
				templateMessage.addData(new WxMpTemplateData("keyword2", "学习时长约10分钟\r\n\r\n", "#000000"));
				templateMessage.addData(new WxMpTemplateData("remark", "点击下方【今日阅读】，完成今日的学习，每天坚持一点点，做更好的自己！\r\n\r\n↓↓↓", "#000000"));
				wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
				return 1;
			}
		} catch (Exception e) {
			logger.error("=======> 用户信息发送异常" + user.getNickname() +" : " + user.getOpenid() +" " + e.getMessage() );
		}
		return 0;
	}
	
	

}
